package com.zxy.supplier_system.server.controller

import com.zxy.supplier_system.server.controller.MarketSaleDocumentController.MarketSaleDocumentDetail
import com.zxy.supplier_system.server.controller.MarketSaleDocumentsItemController.Companion.importExcelToList
import com.zxy.supplier_system.server.entity.Authority
import com.zxy.supplier_system.server.entity.MarketSaleDocument
import com.zxy.supplier_system.server.service.MarketSaleDocumentService
import com.zxy.supplier_system.server.utils.IntIdAndName
import org.springframework.data.domain.Page
import org.springframework.data.domain.PageRequest
import org.springframework.data.domain.Pageable
import org.springframework.data.domain.Sort
import org.springframework.web.bind.annotation.*
import org.springframework.web.multipart.MultipartFile
import java.time.OffsetDateTime


@RestController
@RequestMapping("markets/accounts/{accountId}/saleDocuments")
class MarketAccountsSaleDocumentController(
    private val marketSaleDocumentService: MarketSaleDocumentService
) {

    class CreateMarkerReturnOrderRequest(
        val note: String?,
        val month: Int,
        val year: Int,
    )

    @HasAuthority(Authority.卖场_销售单_查询)
    @GetMapping("year/{year}/month/{month}")
    fun getMarketSaleDocumentDetail(
        @PathVariable accountId: Int,
        @PathVariable year: Int,
        @PathVariable month: Int,
        includeItems: Boolean = false
    ): MarketSaleDocumentDetail {
        return this.marketSaleDocumentService.getMarketSaleDocumentDetail(accountId, year, month, includeItems)
    }

    @HasAnyAuthority(Authority.卖场_销售单_修改, Authority.卖场_销售单_开单)
    @PostMapping("year/{year}/month/{month}/items/excel/import")
    fun importExcel(
        @RequestParam file: MultipartFile,
        @PathVariable accountId: Int,
        @PathVariable year: Int,
        @PathVariable month: Int,
    ) {
        val goodsItems = importExcelToList(file)

        return this.marketSaleDocumentService.importFromExcel(accountId, year, month, goodsItems)
    }

    @HasAnyAuthority(Authority.卖场_销售单_修改)
    @DeleteMapping("year/{year}/month/{month}/items")
    fun clear(
        @PathVariable accountId: Int,
        @PathVariable year: Int,
        @PathVariable month: Int,
    ) {
        return this.marketSaleDocumentService.clear(accountId, year, month)
    }

    @HasAnyAuthority(Authority.卖场_销售单_开单)
    @PostMapping
    fun createMarketSaleDocument(
        @PathVariable accountId: Int,
        @RequestBody request: CreateMarkerReturnOrderRequest
    ): Long {
        return this.marketSaleDocumentService.createMarketSaleDocument(accountId, request)
    }

    @HasAnyAuthority(Authority.卖场_销售单_查询)
    @GetMapping
    fun queryMarketSaleDocumentInAccount(
        @PathVariable accountId: Int,
        pageable: Pageable,
        request: MarketSaleDocumentController.QueryMarketSaleDocumentRequest
    ): Page<QueryMarketSaleDocumentInMarketResponse> {
        fun preHandlePageable(pageable: Pageable): Pageable {
            val originalSort = pageable.sort


            // 如果没有排序或者不包含yearMonth字段，直接返回原Pageable
            if (originalSort.isUnsorted || originalSort.stream()
                    .anyMatch({ order -> "yearMonth" == order.property })
            ) {
                return pageable
            }


            // 构建新的Sort对象
            val newOrders = ArrayList<Sort.Order>()

            for (order in originalSort) {
                if ("yearMonth" == order.property) {
                    // 将yearMonth拆分为year和month的排序
                    newOrders.add(Sort.Order(order.direction, "year"))
                    newOrders.add(Sort.Order(order.direction, "month"))
                } else {
                    // 其他字段保持原样
                    newOrders.add(order)
                }
            }

            val newSort: Sort = Sort.by(newOrders)
            return PageRequest.of(
                pageable.pageNumber,
                pageable.pageSize,
                newSort
            );
        }

        return this.marketSaleDocumentService.queryMarketSaleDocumentInAccount(
            accountId,
            preHandlePageable(pageable),
            request
        )
    }

    data class QueryMarketSaleDocumentInMarketResponse(
        val id: Long,
        val createdBy: IntIdAndName,
        val createdDateTime: OffsetDateTime,
        val goodsKindAmount: Int,
        val submittedDateTime: OffsetDateTime?,
        val status: MarketSaleDocument.Status,
        val year: Int,
        val month: Int,
    )

    @GetMapping("createdBys", params = ["projection=summary"])
    fun queryOrderCreatedEmployeesByAccountId(@PathVariable accountId: Int): List<IntIdAndName> {
        return this.marketSaleDocumentService.queryOrderCreatedEmployeesByMarketId(accountId)
    }

    data class MoveGoodsRequest(
        val targetAccountId: Int,
    )

    @PostMapping("year/{year}/month/{month}/goods/{goodsId}/move")
    fun moveGoodsToAnotherSaleDocument(
        @PathVariable goodsId: Int,
        @PathVariable accountId: Int,
        @PathVariable year: Int,
        @PathVariable month: Int,
        @RequestBody request: MoveGoodsRequest,
    ) {
        return this.marketSaleDocumentService.move(goodsId, accountId, year, month, request)
    }

    data class MoveMultiGoodsRequest(
        val goodsIds: List<Int>,
        val targetAccountId: Int,
    )

    @PostMapping("year/{year}/month/{month}/goods/move")
    fun moveGoodsToAnotherSaleDocument(
        @PathVariable accountId: Int,
        @PathVariable year: Int,
        @PathVariable month: Int,
        @RequestBody request: MoveMultiGoodsRequest,
    ) {
        return this.marketSaleDocumentService.move(accountId, year, month, request)
    }


}